<template>
  <div>
    <a-card title="销售记录">
      <a-form-model
        ref="form"
        :model="searchForm"
        :rules="rules"
        :label-col="{ span: 8 }"
        :wrapper-col="{ span: 16 }"
      >
        <a-row gutter="24">
          <a-col
            :span="4"
            :md="8"
            :xl="6"
            style="
              padding-left: 0px;
              padding-right: 0px;
              width: 200px;
              margin-right: 0px;
              margin-left: 0px;
            "
          >
            <a-form-model-item prop="is_void" label="订单状态">
              <a-select
                v-model="searchForm.is_void"
                style="width: 100%"
                placeholder="订单状态"
                allowClear
              >
                <a-select-option
                  v-for="item in is_Void_Options"
                  :key="item.id"
                  :value="item.value"
                >
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col
            :span="4"
            :md="8"
            :xl="6"
            style="
              padding-left: 0px;
              padding-right: 0px;
              width: 190px;
              margin-right: 0px;
              margin-left: 5px;
            "
          >
            <a-form-model-item prop="qualification_status" label="是否付款">
              <a-select
                v-model="searchForm.qualification_status"
                style="width: 100%"
                placeholder="是否付款"
                allowClear
              >
                <a-select-option
                  v-for="item in qualification_status_Options"
                  :key="item.id"
                  :value="item.value"
                >
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col
            :span="4"
            :md="8"
            :xl="6"
            style="
              padding-left: 0px;
              padding-right: 0px;
              width: 200px;
              margin-right: 0px;
              margin-left: 0px;
            "
          >
            <a-form-model-item prop="client" label="客户">
              <a-select
                showSearch
                v-model="searchForm.client"
                style="width: 100%"
                :filterOption="filterOption"
                allowClear
              >
                <a-select-option
                  v-for="item in clientsItems"
                  :key="item.id"
                  :value="item.id"
                >
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col
            :span="3"
            :md="3"
            :xl="3"
            style="
              padding-left: 0px;
              padding-right: 0px;
              width: 180px;
              margin-right: 0px;
            "
          >
            <a-form-model-item prop="search" label="搜索">
              <a-input
                v-model="searchForm.search"
                allowClear
                placeholder="单号,客户编号"
                style="
                  padding-left: 0px;
                  padding-right: 0px;
                  width: 180px;
                  margin-right: 0px;
                "
              />
              <!-- <a-input v-model="searchForm.search" allowClear :placeholder="NewdateToString" /> -->
            </a-form-model-item>
          </a-col>
          <a-col
            :span="3"
            :md="3"
            :xl="3"
            style="
              padding-left: 0px;
              padding-right: 0px;
              width: 280px;
              margin-right: 0px;
              margin-left: 50px;
            "
          >
            <a-form-model-item label="处理日期">
              <a-range-picker
                v-model="dateRange"
                @change="changeDate"
                style="width: 200px"
                :ranges="ranges"
              />
            </a-form-model-item>
          </a-col>
          <a-col
            :span="3"
            :md="3"
            :xl="3"
            style="width: 280px; margin-left: 10px"
          >
            <a-form-model-item>
              <a-button-group>
                <a-button type="primary" :loading="loading" @click="search"
                  ><a-icon type="search" />查询</a-button
                >
                <a-button :loading="downloadLoading" @click="handleDownload"
                  ><a-icon type="file-excel" />导出</a-button
                >
              </a-button-group>
            </a-form-model-item>
          </a-col>
          <a-col :span="3" :md="3" :xl="3" style="margin-left: -100px">
            <div style="position: relative; z-index: 999; height: 32px">
              <a-form-model-item prop="fields" label="下载选项:">
                <a-select
                  v-model="fields"
                  mode="multiple"
                  allowClear
                  style="
                    width: 100%;
                    height: 32px;
                    overflow: hidden;
                    margin-top: 5px;
                  "
                  @change="fieldsChange"
                >
                  <a-select-option
                    v-for="item in tHeader_filterVal"
                    :key="item.id"
                    :value="item.id"
                    >{{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </div>
          </a-col>

          <!-- <a-col :span="24" :md="8" :xl="6" style="max-width: 256px; margin-bottom: 12px;">
          <a-range-picker @change="onChangePicker" />
        </a-col> -->
        </a-row>
      </a-form-model>
      <a-row style="margin-top: 0px">
        查询结果-> 订单量：共{{ total.count }}(单)，材料费总金额：{{
          total.total_clAmount
        }}(元)，加工费总金额：{{ total.total_jgAmount }}(元)，合计总金额：{{
          total.total_amount
        }}(元)，
        <span style="color: green; font-weight: bolder"
          >已付款：{{ total.collection_amount }}(元)，</span
        >
        <span style="color: red; font-weight: bolder"
          >未付款：{{
            (total.total_amount - total.collection_amount).toFixed(2)
          }}(元)</span
        >
      </a-row>
      <a-row style="margin-top: 12px">
        <a-table
          size="small"
          :columns="columns"
          :dataSource="items"
          rowKey="id"
          :loading="loading"
          :pagination="pagination"
          :summary="true"
          @change="tableChange"
        >
          <div slot="is_void" slot-scope="value">
            <a-tag :color="get_tag_parm(value).color">{{
              get_tag_parm(value).status
            }}</a-tag>
          </div>
          <div slot="qualification_status" slot-scope="value">
            <a-tag :color="get_tag_qualification_status(value).color">{{
              get_tag_qualification_status(value).status
            }}</a-tag>
          </div>
          <div slot="action" slot-scope="value, item">
            <a-button-group size="small">
              <a-button size="small" @click="detial(item)">打印</a-button>
              <a-button size="small" @click="modify(item)">修改</a-button>
              <a-popconfirm
                title="确定作废吗"
                @confirm="voidItem(item)"
                v-if="!item.is_void && is_void_may"
              >
                <a-button type="danger" icon="delete" size="small"
                  >作废</a-button
                >
              </a-popconfirm>
            </a-button-group>
          </div>
          <!-- <template slot="footer">
              <template slot-scope="{ columns, items }">
                  <tr>
                    <td v-for="(column,index) in columns" :key="index">
                      <strong>合计</strong>
                    </td>
                    <td>{{ items.length }}</td>
                  </tr>
              </template>
          </template> -->
        </a-table>
      </a-row>
    </a-card>
  </div>
</template>

<script>
import { saleOrderList, saleOrdersVoid } from "@/api/sale";
import { clientsOption } from "@/api/option";
import { List } from "@/api/common";
import { datetimeToString,filterOption} from "@/utils/common";
import moment from "moment";
import { pinyin } from "pinyin-pro";
export default {
  name: "SaleRecord",
  components: {},
  data() {
    return {
      tHeader_filterVal: [
        { id: 1, name: "序号", field: "index" },
        { id: 2, name: "销售编号", field: "number" },
        { id: 3, name: "客户", field: "client_name" },
        { id: 4, name: "材料费(元)", field: "clAmount_sum" },
        { id: 5, name: "加工费(元)", field: "jgAmount_sum" },
        { id: 6, name: "合计金额(元)", field: "total_amount" },
        { id: 7, name: "收款金额", field: "collection_amount" },
        { id: 8, name: "订单状态", field: "is_void" },
        { id: 9, name: "是否付款", field: "qualification_status" },
        { id: 10, name: "收款账户", field: "account_name" },
        { id: 11, name: "经手人", field: "handler_name" },
        { id: 12, name: "处理时间", field: "create_time" },
      ],
      fields: [1, 2, 3, 4, 5, 6, 7, 9, 11, 12],
      ranges: {
        今日: [moment().startOf("day"), moment().startOf("day")],
        昨日: [moment().subtract(1, "days"), moment().subtract(1, "days")],
        本周: [
          moment().week(moment().week()).startOf("week"),
          moment().week(moment().week()).endOf("week"),
        ],
        上周: [
          moment().subtract(1, "week").startOf("week"),
          moment().subtract(1, "week").endOf("week"),
        ],
        本月: [moment().startOf("month"), moment().startOf("day")],
        上月: [
          moment().subtract(1, "month").startOf("month"),
          moment().subtract(1, "month").endOf("month"),
        ],
      },
      downloadLoading: false,
      downloadList: [],
      columns: [
        {
          title: "序号",
          dataIndex: "index",
          key: "index",
          customRender: (value, item, index) => {
            return (
              (this.pagination.current - 1) * this.pagination.pageSize +
              index +
              1
            );
          },
          width: 45,
        },
        {
          title: "销售编号",
          dataIndex: "number",
          sorter: true,
        },
        {
          title: "客户",
          dataIndex: "client_name",
        },
        {
          title: "经手人",
          dataIndex: "handler_name",
        },
        {
          title: "处理日期",
          dataIndex: "handle_time",
          width: 150,
          sorter: true,
        },
        {
          title: "材料费(元)",
          dataIndex: "clAmount_sum",
          width: 120,
          customRender: (value, item) => {
            return NP.round(value, 2);
          },
        },
        {
          title: "加工费(元)",
          dataIndex: "jgAmount_sum",
          width: 120,
          customRender: (value, item) => {
            return NP.round(value, 2);
          },
        },
        {
          title: "合计金额(元)",
          dataIndex: "total_amount",
          width: 120,
          customRender: (value, item) => {
            return NP.round(value, 2);
          },
        },
        {
          title: "收款金额",
          dataIndex: "collection_amount",
          width: 120,
          customRender: (value, item) => {
            return NP.round(value, 2);
          },
        },
        {
          title: "订单状态",
          dataIndex: "is_void",
          key: "is_void",
          width: 120,
          align: "center",
          scopedSlots: { customRender: "is_void" },
        },
        {
          title: "是否已付款",
          dataIndex: "qualification_status",
          key: "qualification_status",
          width: 120,
          align: "center",
          scopedSlots: { customRender: "qualification_status" },
        },
        {
          title: "操作",
          dataIndex: "action",
          scopedSlots: { customRender: "action" },
          width: 200,
        },
      ],
      total: {
        count: 0,
        total_amount: 0,
        collection_amount: 0,
      },
      dateRange: [moment().startOf("day"), moment().startOf("day")],
      clientsItems: [],
      // dateRange: [moment().startOf('day'), moment().startOf('day')],//获取本月开始第一天到今天
      searchForm: {
        page: 1,
        page_size: 15,
        is_void: false,
        search: null,
        qualification_status: null,
        client: null,
        ordering: "handle_time",
      },
      pagination: { current: 1, total: 0, pageSize: 15 },
      loading: false,
      items: [],
      visible: false,
      targetItem: {},
      form: {},
      is_Void_Options: [
        {
          id: 1,
          name: "所有",
          value: null,
        },
        {
          id: 2,
          name: "正常",
          value: false,
        },
        {
          id: 3,
          name: "已作废",
          value: true,
        },
      ],
      qualification_status_Options: [
        {
          id: 1,
          name: "所有",
          value: null,
        },
        {
          id: 2,
          name: "未付",
          value: false,
        },
        {
          id: 3,
          name: "已付",
          value: true,
        },
      ],
    };
  },
  computed: {
    tHeader_filterVal_new() {
      return this.tHeader_filterVal
        .filter((item) => this.fields.includes(item.id))
        .sort((a, b) => a.id - b.id);
    },
    NewdateToString() {
      let ndate = new Date();
      var month = ndate.getMonth() + 1;
      var day = ndate.getDate();
      return (
        (String(month).length > 1 ? month : "0" + month) +
        "" +
        (String(day).length > 1 ? day : "0" + day)
      );
    },
    // 是否可以作废的标识
    is_void_may() {
      console.log(this.NewdateToString);
      return this.searchForm.search == this.NewdateToString;
    },
  },
  methods: {
    // 将输入的内容与显示的内容进行匹配
    filterOption(value, option) {
      return filterOption(value, option) 
    },
    getNewdownloadList(downloadList) {
      let o = {
        index: "合计",
        total_quantity: 0,
        clAmount_sum: 0,
        jgAmount_sum: 0,
        total_amount: 0,
        collection_amount: 0,
      };
      downloadList.forEach((e) => {
        e.is_void = e.is_void ? "已作废" : "正常";
        e.qualification_status = e.qualification_status ? "已付款" : "未付款";
      });
      if (downloadList) {
        let i = 0;
        downloadList.forEach((e) => {
          i += 1;
          e["index"] = i;
          o.total_quantity += parseFloat(e.total_quantity);
          o.clAmount_sum += parseFloat(e.clAmount_sum);
          o.jgAmount_sum += parseFloat(e.jgAmount_sum);
          o.total_amount += parseFloat(e.total_amount);
          o.collection_amount += parseFloat(e.collection_amount);
        });
        downloadList.push(o);
      } else {
        downloadList = [];
      }
    },
    handleDownload() {
      this.loading = true;
      this.downloadLoading = true;
      this.searchForm.start_date =
        this.dateRange.length > 0
          ? this.dateRange[0].format("YYYY-MM-DD")
          : null;
      this.searchForm.end_date =
        this.dateRange.length > 0
          ? this.dateRange[1].format("YYYY-MM-DD")
          : null;
      this.searchForm.page_size = 9999;
      if (this.searchForm.end_date) {
        this.searchForm.end_date = moment(this.searchForm.end_date)
          .add(1, "days")
          .format("YYYY-MM-DD");
      }
      List(this.searchForm, "sales_orders_list").then((response) => {
        const resp = response.data;
        this.downloadList = response.results;
        this.getNewdownloadList(this.downloadList);
        // this.downloadList.forEach(e => {
        //     e.jgry_items=this.jgry_items2names(e.jgry_items)
        //     e.is_void=e.is_void?'已作废':"正常"
        // });
        // console.log('this.downloadList:',this.downloadList )
        this.searchForm.page_size = 15;
        import("@/vendor/Export2ExcelNew").then((excel) => {
          let tHeader1 = [];
          let filterVal = [];
          this.tHeader_filterVal_new.forEach((e) => {
            tHeader1.push(e.name);
            filterVal.push(e.field);
          });
          const merges = [
            `A1:${String.fromCharCode(
              64 + this.tHeader_filterVal_new.length
            )}1`,
          ];
          //不要将下载数据与显示数据列表用同一个变量，否则要出问题
          const list = this.downloadList;
          let downloadList = list;
          const data = this.formatJson(filterVal, downloadList);
          console.log("data:", data);
          const title = ["销售记录" + datetimeToString(new Date())];
          const sheetname = "销售记录";
          excel.export_json_to_excel({
            title,
            header: tHeader1,
            // multiHeader:[tHeader1],
            data,
            filename: "销售记录" + datetimeToString(new Date()),
            merges,
            // autoWidth: this.autoWidth,
            autoWidth: this.autoWidth,
            bookType: this.bookType,
            sheetname,
          });
          this.loading = false;
          this.downloadLoading = false;
        });
      });
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map((v) =>
        filterVal.map((j) => {
          if (j === "timestamp") {
            return parseTime(v[j]);
          } else {
            return v[j];
          }
        })
      );
    },
    summary() {
      this.items.push({
        number: "合计",
        arrears_amount: "",
        client_name: 1000,
        creator_name: "",
      });
      console.log(this.items);
    },
    get_tag_parm(value) {
      let color = "green";
      let status = "正常";
      if (value) {
        color = "red";
        status = "已作废";
      }
      return { color, status };
    },
    get_tag_qualification_status(value) {
      let color = "red";
      let status = "未付款";
      if (value) {
        color = "green";
        status = "已付款";
      }
      return { color, status };
    },
    initialize() {
      clientsOption({ page_size: 999999, is_active: true }).then((data) => {
        this.clientsItems = data.results;
      });
      this.getSearchForm();
      this.list();
    },
    getSearchForm() {
      // 如果sessionStorage存在"saleRecordItem"
      let local_saleRecord_searchFormItem = JSON.parse(
        sessionStorage.getItem("saleRecord_searchFormItem")
      );
      if (local_saleRecord_searchFormItem) {
        this.searchForm = local_saleRecord_searchFormItem;
        let dateRange = JSON.parse(
          sessionStorage.getItem("saleRecord_dateRangeItem")
        );
        if (dateRange) {
          this.dateRange =
            dateRange.length > 0
              ? [moment(dateRange[0]), moment(dateRange[1])]
              : [];
        }
        this.pagination.current = this.searchForm.page;
        this.pagination.pageSize = this.searchForm.page_size;
      } else {
        this.searchForm.start_date =
          this.dateRange.length > 0
            ? this.dateRange[0].format("YYYY-MM-DD")
            : null;
        this.searchForm.end_date =
          this.dateRange.length > 0
            ? this.dateRange[1].format("YYYY-MM-DD")
            : null;
        if (this.searchForm.end_date) {
          this.searchForm.end_date = moment(this.searchForm.end_date)
            .add(1, "days")
            .format("YYYY-MM-DD");
        }
      }
    },
    list() {
      this.loading = true;
      saleOrderList(this.searchForm)
        .then((data) => {
          this.pagination.total = data.count;
          this.total.count = data.count;
          this.total.total_clAmount = data.total_clAmount;
          this.total.total_jgAmount = data.total_jgAmount;
          this.total.total_amount = data.total_amount;
          this.total.collection_amount = data.collection_amount;
          this.items = data.results;
          // this.summary()
        })
        .finally(() => {
          this.loading = false;
        });
    },
    tableChange(pagination, filters, sorter) {
      this.searchForm.page = pagination.current;
      this.pagination.current = pagination.current;
      this.searchForm.ordering = `${sorter.order == "descend" ? "-" : ""}${
        sorter.field
      }`;
      sessionStorage.setItem(
        "saleRecord_searchFormItem",
        JSON.stringify(this.searchForm)
      );
      sessionStorage.setItem(
        "saleRecord_dateRangeItem",
        JSON.stringify(this.dateRange)
      );
      this.list();
    },
    onChangePicker(date, dateString) {
      let startDate = date[0],
        endDate = date[1];
      this.searchForm.start_date = startDate
        ? startDate.format("YYYY-MM-DD")
        : undefined;
      this.searchForm.end_date = endDate
        ? endDate.add(1, "days").format("YYYY-MM-DD")
        : undefined;
      this.search();
    },
    search() {
      this.searchForm.page = 1;
      this.pagination.current = 1;
      this.searchForm.start_date =
        this.dateRange.length > 0
          ? this.dateRange[0].format("YYYY-MM-DD")
          : null;
      this.searchForm.end_date =
        this.dateRange.length > 0
          ? this.dateRange[1].format("YYYY-MM-DD")
          : null;
      if (this.searchForm.end_date) {
        this.searchForm.end_date = moment(this.searchForm.end_date)
          .add(1, "days")
          .format("YYYY-MM-DD");
      }
      sessionStorage.setItem(
        "saleRecord_searchFormItem",
        JSON.stringify(this.searchForm)
      );
      this.dateRange.length > 0
        ? sessionStorage.setItem(
            "saleRecord_dateRangeItem",
            JSON.stringify(this.dateRange)
          )
        : {};
      this.list();
    },
    detial(item) {
      this.$router.push({
        path: "/sale/sale_record_detail",
        query: { id: item.id },
      });
    },
    view(item) {
      this.$router.push({
        path: "/sale/sale_record_view",
        query: { id: item.id },
      });
    },
    modify(item) {
      this.$router.push({
        path: "/sale/sale_record_modify",
        query: { id: item.id },
      });
    },
    voidItem(item) {
      saleOrdersVoid({ id: item.id }).then(() => {
        this.$message.success("作废成功");
        this.searchForm.search = null;
        this.list();
      });
    },
  },
  mounted() {
    this.initialize();
  },
};
</script>